<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="1500" destroy-on-close :close-on-press-escape="mode != 'show' ? false : true" @closed="$emit('closed')" align-center>
        <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="100" ref="dialogForm">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="入库单号" prop="other_code">
                        <el-input v-model="form.other_code" placeholder="入库单号(不填写自动生成)" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="入库名称" prop="other_name">
                        <el-input v-model="form.other_name" placeholder="请输入入库名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="入库日期" prop="other_date">
                        <el-date-picker v-model="form.other_date" type="date" placeholder="请选择入库日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="仓库" prop="ware_id">
                        <el-select v-model="ware_id" filterable style="width: 100%" placeholder="仓库" @change="wareChange" clearable>
                        <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" clearable></el-input>
                </el-form-item>
            </el-col>
            <el-form-item label="入库产品清单" prop="detail">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="checkProduct" v-if="mode!='turn'">选择产品</el-button>
                <sc-form-table ref="table" v-model="form.detail" :addTemplate="addTemplate" placeholder="暂无数据" height="400" hideAdd show-summary>
                    <el-table-column label="品名" align="center">
                        <template #default="scope">
                            {{ scope.row.goods_name }}
                        </template>
                    </el-table-column>
                    <el-table-column label="规格" align="center">
                        <template #default="scope">
                            {{ scope.row.goods_spec }}
                        </template>
                    </el-table-column>
                    <el-table-column label="产品单位" align="center">
                        <template #default="scope">
                            {{ scope.row.unit_name }}
                        </template>
                    </el-table-column>
                    <el-table-column label="品牌" align="center">
                        <template #default="scope">
                            {{ scope.row.brand_name }}
                        </template>
                    </el-table-column>
                    <el-table-column label="数量" prop="number" align="center">
                        <!-- <template #default="scope">
                            <el-input v-model="scope.row.number" placeholder="数量" @input="totalCompute" @focus="onFocus($event)"></el-input>
                        </template> -->
                        <template #default="scope">
                            <el-input 
                                v-model="scope.row.number" 
                                placeholder="数量" 
                                @input="totalCompute" 
                                @focus="onFocus($event)"
                                @keydown.enter="handleArrowRightKey(scope.$index, 'number')"
                                @keydown.up="up(scope.$index, 'number')"
                                @keydown.down="down(scope.$index, 'number')"
                                @keydown.left="handleArrowLeftKey(scope.$index, 'number')"
                                @keydown.right="handleArrowRightKey(scope.$index, 'number')"
                                :id="`number${scope.$index}`"
                                :ref="`number${scope.$index}`"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="单价" prop="price" align="center">
                        <!-- <template #default="scope">
                            <el-input v-model="scope.row.price" placeholder="单价" @input="totalCompute" @focus="onFocus($event)"></el-input>
                        </template> -->
                        <template #default="scope">
                            <el-input 
                                v-model="scope.row.price" 
                                placeholder="单价" 
                                @input="totalCompute"
                                @focus="onFocus($event)"
                                @keydown.enter="handleArrowRightKey(scope.$index, 'price')"
                                @keydown.up="up(scope.$index, 'price')"
                                @keydown.down="down(scope.$index, 'price')"
                                @keydown.left="handleArrowLeftKey(scope.$index, 'price')"
                                @keydown.right="handleArrowRightKey(scope.$index, 'price')"
                                :id="`price${scope.$index}`"
                                :ref="`price${scope.$index}`"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="金额" prop="fee" align="center">
                        <!-- <template #default="scope">
                            <el-input v-model="scope.row.fee" placeholder="金额" @input="feeCompute" @focus="onFocus($event)"></el-input>
                        </template> -->
                        <template #default="scope">
                            <el-input 
                                v-model="scope.row.fee" 
                                placeholder="金额" 
                                @input="feeCompute"
                                @focus="onFocus($event)"
                                @keydown.enter="handleArrowRightKey(scope.$index, 'fee')"
                                @keydown.up="up(scope.$index, 'fee')"
                                @keydown.down="down(scope.$index, 'fee')"
                                @keydown.left="handleArrowLeftKey(scope.$index, 'fee')"
                                @keydown.right="handleArrowRightKey(scope.$index, 'fee')"
                                :id="`fee${scope.$index}`"
                                :ref="`fee${scope.$index}`"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="仓库" align="center">
                        <template #default="scope">
                            <el-select v-model="scope.row.ware_id" filterable style="width: 100%" placeholder="仓库">
                                <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id"/>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" prop="remark" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.remark" placeholder="备注"></el-input>
                        </template>
                    </el-table-column>
                </sc-form-table>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="visible=false">取 消</el-button>
            <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
        </template>
    </el-dialog>
    <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false" :query="{system_disable:0,stock_ware: ware_id}"></select-goods>
</template>

<script>
import selectGoods from '@/views/goods/info/selectGoods.vue';

export default {
    components: {selectGoods},
    emits: ['success', 'closed'],
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '新增',
                edit: '编辑',
                show: '查看',
            },
            visible: false,
            isSaveing: false,
            form: {
                id: "",
                other_code: "",
                other_name: "",
                other_type: 1,
                remark: "",
                other_date: this.moment().format('YYYY-MM-DD'),
                detail: [],
            },
            addTemplate: {},
            dialog: {
                goods: false,
            },
            wareList: [],
            ware_id: "",
            column: [
                {prop: "number",name: "数量",},
                {prop: "price",name: "单价",},
                {prop: "fee",name: "金额",},
            ],
        }
    },
    mounted() {
        this.getWare()
    },
    methods: {
        //显示
        open(mode = 'add') {
        this.mode = mode;
        this.visible = true;
        return this
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    var res = [];
                    if (this.form.id) {
                        res = await this.$API.ware.other.edit.post(this.form);
                    } else {
                        res = await this.$API.ware.other.add.post(this.form);
                    }
                    this.isSaveing = false;
                    if (res != '') {
                        if (res.code == 1) {
                        this.$emit('success', this.form, this.mode)
                        this.visible = false;
                        this.$message.success("操作成功")
                        } else {
                        this.$alert(res.message, "提示", {type: 'error'})
                        }
                    }
                }
            })
        },
        //表单注入数据
        async setData(data) {
            this.form.id = data.other_id
            var res = await this.$API.ware.other.detail.get({id: data.other_id});
            this.form.other_code = res.data.other_code
            this.form.other_name = res.data.other_name
            this.form.other_date = res.data.other_date
            this.form.remark = res.data.remark
            let array = []
            res.data.detail.map(item => {
                array.push({
                    id: item.id,
                    goods_id: item.goods_id,
                    goods_name: item.goods && item.goods.goods_name,
                    goods_spec: item.goods && item.goods.goods_spec,
                    unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
                    brand_name: item.goods && item.goods.brand && item.goods.brand.brand_name,
                    goods_code: item.goods && item.goods.goods_code,
                    number: item.number,
                    price: item.price,
                    fee: item.fee,
                    ware_id: item.ware_id,
                    remark: item.remark,
                })
            })
            this.form.detail = array
        },
        // 选择产品
        checkProduct() {
            this.dialog.goods = true
            this.$nextTick(() => {
                this.$refs.goodsDialog.open('add')
            })
        },
        // 选择产品返回
        goodsUpdate(data) {
            let array = []
            if(Array.isArray(data)){
                data.map((item) => {
                    array.push({
                    goods_id: item.id,
                    goods_name: item.goods_name,
                    goods_spec: item.goods_spec,
                    unit_name: item.unit && item.unit.unit_name,
                    brand_name: item.brand && item.brand.brand_name,
                    mater_code: item.material_code,
                    goods_code: item.goods_code,
                    price: item.cost_price,
                    ware_id: this.ware_id ? this.ware_id : '',
                    })
                })
            }else {
                array.push({
                    goods_id: data.id,
                    goods_name: data.goods_name,
                    goods_spec: data.goods_spec,
                    unit_name: data.unit && data.unit.unit_name,
                    brand_name: data.brand && data.brand.brand_name,
                    mater_code: data.material_code,
                    goods_code: data.goods_code,
                    price: data.cost_price,
                    ware_id: this.ware_id ? this.ware_id : '',
                })
            }
            let existingIds = this.form.detail.map(item => item.goods_id);
            for (let i = array.length - 1; i >= 0; i--) {
                if (existingIds.includes(array[i].goods_id)) {
                array.splice(i, 1);
                }
            }
            this.form.detail = [...this.form.detail, ...array]
        },
        onFocus(event) {
            event.target.select();
        },
        // 获取仓库
        async getWare() {
            var res = await this.$API.goods.ware.all.get();
            this.wareList = res.data;
            if (this.mode == 'add') {
                res.data.map(item => {
                if (item.is_default == 1) {
                    this.ware_id = item.id
                }
                })
            }
        },
        wareChange(e) {
            this.form.detail.map(item => item.ware_id = e)
        },
        totalCompute(){
            this.form.detail.map(item => {
                if (item.price && item.number) {
                    item.fee = (Number(item.price) * Number(item.number)).toFixed(2)
                }
            })
        },
        feeCompute(){
            this.form.detail.map(item => {
                if (item.fee && item.number) {
                    item.price = (Number(item.fee) / Number(item.number)).toFixed(2)
                }
            })
        },
        // 数量上
        up(index, field) {
            let prevField = ''
            if (index > 0) {
                // const prevField = this.$refs[field][index - 1];
                prevField = this.$refs[`${field}${index-1}`];
            } else {
                prevField = this.$refs[`${field}${this.form.detail.length-1}`];
            }
            prevField.focus();
            setTimeout(() => {
                prevField.select();
            },0)
        },
        // 数量下
        down(index, field) {
            let prevField = ''
            if (index < this.form.detail.length - 1) {
                prevField = this.$refs[`${field}${index+1}`];
            } else {
                prevField = this.$refs[`${field}${0}`];
            }
            prevField.focus();
            setTimeout(() => {
                prevField.select();
            },0)
        },
        handleArrowLeftKey(event, field) {
            let newFeield = '';
            for (let i = 0; i < this.column.length; i++) {
                if (field == this.column[0].prop) {
                    newFeield = this.column[this.column.length-1].prop
                }else{
                    if (field == this.column[i].prop) {
                        for (let j = 0; j < this.column.length; j++) {
                            if ( j<i) {
                                newFeield = this.column[j].prop
                            }
                        }
                    }
                }
            }
            console.log('newFeield :>> ', newFeield);
            let prevField = ''
            prevField = this.$refs[newFeield + event];
            if(prevField){
                prevField.focus();
                setTimeout(() => {
                    prevField.select();
                },0)
            }else{
                console.log('无了');
            }
        },
        handleArrowRightKey(event, field) {
            let newFeield = '';
            for (let i = 0; i < this.column.length; i++) {
                if (field == this.column[this.column.length-1].prop) {
                    newFeield = this.column[0].prop
                }else{
                    if (field == this.column[i].prop) {
                        for (let j = 0; j < this.column.length; j++) {
                            if ( j>i) {
                                newFeield = this.column[j].prop
                                break
                            }
                        }
                    }
                }
            }
            let prevField = ''
            prevField = this.$refs[newFeield + event];
            if(prevField){
                console.log('到了');
                prevField.focus();
                setTimeout(() => {
                    prevField.select();
                },0)
            }else{
                console.log('无了');
            }
        },
    }
}
</script>

<style>
</style>
